<?php
/**
 * Created by PhpStorm.
 * User: yu
 * Date: 2017/8/12
 * Time: 上午9:30
 */

namespace app\lib\exception;


use think\Exception;
use think\exception\Handle;
use think\Log;
use think\Request;

class ExceptionHandler extends Handle
{
	private $code;
	private $error_code;
	private $msg;
	//还需要返回客户端当前请求的url路径
	//覆盖默认的异常处理的方法。所有的异常都通过它来处理
	public function render(Exception $e){
		//如果是BaseException 那么需要返回具体错误信息给客户端
		if($e instanceof BaseException){
			//处理自定义异常
			$this->code = $e->code;
			$this->msg = $e->msg;
			$this->error_code = $e->error_code;
		}else{

			if(config('app_debug')){
				return parent::render($e);
			}else{
				$this->code = 500;
				$this->msg = '服务端错误';
				$this->error_code = 999;
				$this->logRecord($e);
			}

		}
		$request = Request::instance();
		$res = [
			'error_code'=>$this->error_code,
			'msg'=>$this->msg,
			'url'=>$request->url()
		];
		return json($res,$this->code);
	}

	private function logRecord($e){
		//重新开启记录日志功能
		Log::init([
			'type'  => 'File',
			// 日志保存目录
			'path'  => LOG_PATH,
			// 日志记录级别
			'level' => ['error']
		]);
		Log::record($e->getMessage(),'error');
	}
}